import * as React from 'react';
import { DatePicker, Form, Button, Icon, Select, Drawer, Card } from 'antd';
import moment from 'moment';
import { Empty } from 'antd';
import { setLastSelect } from '../../common/utils';
import { useBusinessList } from '../../hook/businessList';
import InfoCard from '../../component/info-card';
import { barChartTemplate } from '../../component/analysisPanel/template';
import RealTimeChart from './real-time-chart';
import { calcCityDistributionSeriseData, calcAllDistribution, collectSuccessRate, collectAreaSuccessRate, collectAllAvg, calcGeoChartData, HorizonBarChartTemplate, speedGeoChartTemplate } from './calc';
import Chart from '../../component/chart';
import { api } from '../../common/api';
import Overview, { distributionLevels } from '../../component/speed-data-overview';

import './index.less';

const {
    useState,
    useEffect,
    useMemo
} = React;


// 保存cgi请求返回的原始数据
let speedInfo, statusInfo, dayTwoStatusInfo, distribution;

export default function Log(props: {}) {
    const [list, projectId, setProjectId] = useBusinessList(0);
    const [selectDate, setSelectDate] = useState(moment().add(-1, 'days').format("YYYY-MM-DD"));
    const [loading, setLoading] = useState(true);
    const [selectCity, setSelectCity] = useState('');
    const [areaSuccessRate, setAreaSuccessRate] = useState({
        rate: 0,
        compareRate: 0
    });
    const [areaSpeed, setAreaSpeed] = useState({ isps: [], speed: [] });
    const [successRate, setSuccessRate] = useState(0);
    const [successRateCompare, setSuccessRateCompare] = useState(0);
    // 请求次数
    const [requestTimes, setRequestTimes] = useState(0);
    const [requestTimesCompare, setRequestTimesCompare] = useState(0);
    // ALL DATA AVG
    const [avgSpeed, setAvgSpeed] = useState(0);
    const [avgSpeedCompare, setAvgSpeedCompare] = useState(0);
    const [geoChartData, setGeoChartData] = useState({
        data: {},
        maxAvg: 0,
        maxCount: 0
    });
    const [isMapClicked, setIsMapClicked] = useState(false);
    // After click map, is the location has data?
    const [isLocationHasData, setIsLocationHasData] = useState(false);
    const [distributionSeries, setDistributionSeries] = useState([]);

    const reset = () => {
        setAreaSuccessRate(null);
        setAreaSpeed({ isps: [], speed: [] });
        setSelectCity('');
        setIsMapClicked(false);
        setIsLocationHasData(false);
        setDistributionSeries([]);
        setLoading(true);
    }

    useEffect(() => {
        reset();
        async function fetchData() {
            // 获取选中日期n天前的数据
            const fetchNDaysAgoDate = n => {
                return api({
                    method: 'GET',
                    url: `speed-server/${projectId}/static-daily`,
                    params: {
                        date: moment(selectDate).add(n, 'days').format("YYYY-MM-DD")
                    }
                }) as any;
            }
            // 选中日期一天前和两天前的数据
            const [oneDayData, twoDayData] = await Promise.all([fetchNDaysAgoDate(0), fetchNDaysAgoDate(-1)]);
            speedInfo = oneDayData.citySpeed || {};
            statusInfo = oneDayData.cityStatus || {};
            dayTwoStatusInfo = twoDayData.cityStatus || {};
            distribution = oneDayData.cityDistribution || {};
            const [thisAllAvg, cityAvg, requestTimes] = collectAllAvg(speedInfo);
            const [lastDayAllAvg, lastDayCityAvg, lastDayRequestTimes] = collectAllAvg(twoDayData.citySpeed || {});
            const oneDaySuccessRate = collectSuccessRate(statusInfo);
            const twoDaySuccessRate = collectSuccessRate(twoDayData.cityStatus);
            const thisGeoChartData = calcGeoChartData(cityAvg);
            setRequestTimesCompare((requestTimes - lastDayRequestTimes) / lastDayRequestTimes);
            setAvgSpeedCompare((thisAllAvg - lastDayAllAvg) / lastDayAllAvg);
            setRequestTimes(requestTimes);
            setGeoChartData(thisGeoChartData);
            setAvgSpeed(thisAllAvg);
            setSuccessRate(oneDaySuccessRate);
            setSuccessRateCompare((oneDaySuccessRate - twoDaySuccessRate) / twoDaySuccessRate);
            setDistributionSeries(calcAllDistribution(oneDayData.cityDistribution));
            setLoading(false);
        }
        if (projectId !== 0) {
            fetchData();
        }
    }, [projectId, selectDate]);

    function setSelectProjectId(id: number) {
        setProjectId(id);
        setLastSelect(id.toString());
    }
    function changeDate(date, dateString) {
        setSelectDate(dateString);
    }

    const mapClick = param => {
        setIsMapClicked(true);
        setSelectCity(param.name);
    }

    useEffect(() => {
        if (!selectCity) {
            return;
        }
        setIsLocationHasData(statusInfo[selectCity] !== undefined);
        const rate = collectAreaSuccessRate(statusInfo[selectCity]);
        const lastDayRate = collectAreaSuccessRate(dayTwoStatusInfo[selectCity]);
        const compareRate = (rate - lastDayRate) / lastDayRate;
        setAreaSuccessRate({
            rate,
            compareRate
        });
        const allIsp = [], ispSpeed = [];
        for (const isp in speedInfo[selectCity]) {
            allIsp.push(isp + `(${speedInfo[selectCity][isp].count}次)`);
            // avg value maybe null
            ispSpeed.push((speedInfo[selectCity][isp].avg || 0).toFixed(2));
        }
        setAreaSpeed({
            isps: allIsp,
            speed: ispSpeed
        });

    }, [selectCity]);

    const aeraChart = () => {
        switch (true) {
            case isMapClicked === false:
                return (
                    <div>
                        <div className="card-tip">请点击左方地图内圆点，查看区域内测速情况</div>
                        <Empty></Empty>
                    </div>
                );
            case isLocationHasData === false:
                return (
                    <div>
                        <div className="card-tip">该区域内暂无数据，请尝试其他区域</div>
                        <Empty></Empty>
                    </div>
                );
            default:
                const thisCityDistribution = distribution[selectCity];
                return <div className="aera-chart">
                    <Chart option={HorizonBarChartTemplate(`区域运营商速度排行(ms)：${selectCity}`, areaSpeed.speed, areaSpeed.isps)} styleName="half-chart"></Chart>
                    <div className="right">
                        <div className="card-wrap">
                            <InfoCard loading={loading} title={`区域请求成功率：${selectCity}(%)`} num={areaSuccessRate.rate * 100} compareNum={areaSuccessRate.compareRate} bordered={true}></InfoCard>
                        </div>
                        <Chart styleName='area-distribution-chart' option={barChartTemplate(`请求速度分布：${selectCity}`, calcCityDistributionSeriseData(thisCityDistribution), distributionLevels)}></Chart>
                    </div>
                </div>
        }
    }
    return (
        <div className='img-speed'>
            <span>项目选择：</span><Select
                showSearch
                value={projectId}
                onSelect={setSelectProjectId}
                filterOption={(input, option: any) =>
                    option.props.value.toString().toLowerCase().indexOf(input.toLowerCase()) >= 0 ||
                    option.props.title.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
                style={{ width: 260, marginRight: 30 }}
            >
                {
                    list.map((item) => {
                        return (
                            <Select.Option key={item.id.toString()} value={item.id} title={item.name}>
                                {item.id}.{item.name}
                            </Select.Option>
                        )
                    })
                }
            </Select>
            <h3 className="title">实时数据分析</h3>
            <RealTimeChart selectProjectId={projectId} />
            <h3 className="first-title">数据分析日报</h3>
            <DatePicker
                onChange={changeDate}
                disabledDate={date => date > moment()}
                defaultValue={moment().add(-1, 'days')}
            ></DatePicker>
            <h3 className="section-title">数据概览</h3>
            {useMemo(() =>
                <Overview
                    loading={loading}
                    successRate={successRate}
                    successRateCompare={successRateCompare}
                    avg={avgSpeed}
                    avgCompare={avgSpeedCompare}
                    requestTimes={requestTimes}
                    requestTImesCompare={requestTimesCompare}
                    seriesData={distributionSeries}
                ></Overview>, [loading])
            }
            <h3 className="section-title">分地区统计</h3>
            <div className="area-cards-wrap">
                <Card
                    loading={loading}
                    bordered={false}
                    hoverable
                    style={{
                        width: '40%',
                        marginRight: 25,
                        padding: '0px 10px',
                        height: 500,
                    }}
                >
                    <Chart styleName='big-map-chart' clickFunc={mapClick} option={speedGeoChartTemplate('分地区延迟(ms)', geoChartData, ['#5BAD4A', '#F7DC0E'])}></Chart>
                    <div className="guide">
                        <div>颜色越深 -> 延迟越高</div>
                        <div>圆圈越大 -> 访问量越大</div>
                    </div>
                </Card>
                <Icon type="right-circle" style={{ fontSize: 30, marginRight: 25 }} />
                <Card
                    loading={loading}
                    bordered={false}
                    hoverable
                    style={{
                        minWidth: '56%',
                        marginRight: 50,
                        padding: '0px 10px',
                        height: 500
                    }}
                >
                    {aeraChart()}
                </Card>
            </div>
        </div >
    );
}
